package xiang.weiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xiang.weiyu.common.BaseContext;
import xiang.weiyu.mapper.*;
import xiang.weiyu.pojo.*;
import xiang.weiyu.service.OrdersService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;


    @Override
    @Transactional
    public void submit(Orders orders) {
        // orders  order_detail
        // 0、获取用户id
        Long userId = BaseContext.getCurrentId();
        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(qw);

        // 2、查询用户数据 select * from user where id = ?
        User user = userMapper.selectById(userId);

        // 3、根据地址id查询地址数据 select * from address_book where id = ?
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());

        long orderId = IdWorker.getId();//订单号

        BigDecimal amount = new BigDecimal(0);//总价
        // 4、保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shoppingCart : shoppingCarts) {
            // ShoppingCart shoppingCart --> OrderDetail orderDetail
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            // orderId单独设置
            orderDetail.setOrderId(orderId);
            // amount 金额单独设置 数量  *  单价
            BigDecimal price = shoppingCart.getAmount();//菜品/套餐 单价
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());//菜品/套餐 份数
            BigDecimal all = price.multiply(number);//总价
            amount = amount.add(all);//相乘得到总价并赋值给amount
            orderDetail.setAmount(all);//设置订单详细表的总金额
            orderDetailMapper.insert(orderDetail);
        }
        // 5、保存订单数据，有许多数据需要单独设置
        orders.setId(orderId);//ID和订单ID保持一致
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);//用户id
        orders.setAddressBookId(addressBook.getId());
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        //pay_method: 已有
        orders.setAmount(amount);//总金额
        //remark: 已有
        orders.setPhone(addressBook.getPhone());//收货人联系电话
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        this.save(orders);
        // 6、删除当前用户的购物车数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(qw2);
    }

    /**
     * 再来一单功能
     *
     * @param orders id
     */
    @Override
    public void againOrder(Orders orders) {
        //通过订单号查询获得订单详细表集合 orderDetails
        LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(orders.getId() != null, OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(qw);

        //遍历集合，Copy订单详细表内容至购物车对象，随后调用购物车DAO层方法，添加菜品/套餐
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }
}
